import { ref, onUnmounted } from "vue"

/**
 * 一次性定时器hook
 * @returns 
 */
function useTimeOut() {
  let timer = ref<number | undefined>(undefined)
  function setTimer(data: number) {
    timer.value = data
  }

  function startTimeout(cb: Function, interval: number = 300) {
    const timer = setTimeout(cb, interval)
    setTimer(timer)
  }
  function closeTimeout() {
    timer.value && clearTimeout(timer.value)
  }

  onUnmounted(() => {
    closeTimeout()
  })

  return {
    startTimeout,
    closeTimeout
  }
}

/**
 * 循环定时器hook
 * @returns 
 */
function useInterval() {
  let timer = ref<number | undefined>(undefined)
  function setTimer(data: number) {
    timer.value = data
  }

  function startInterval(cb: Function, interval: number = 300) {
    const timer = setInterval(cb, interval)
    setTimer(timer)
  }
  function closeInterval() {
    timer.value && clearInterval(timer.value)
  }

  onUnmounted(() => {
    closeInterval()
  })

  return {
    startInterval,
    closeInterval
  }
}